(() => {
  const STATE_KEY = 'apiProxyState';
  const CHANNEL_FROM_PAGE = '__apiProxyFromPage';
  const CHANNEL_FROM_EXT = '__apiProxyFromExt';

  // Inject hook.js into the page (main world)
  function injectHook() {
    try {
      const s = document.createElement('script');
      s.src = chrome.runtime.getURL('src/pageHook/hook.js');
      s.async = false;
      s.dataset.apProxy = '1';
      (document.documentElement || document.head || document.body).appendChild(s);
      // remove after load to keep DOM clean
      s.onload = () => s.parentNode && s.parentNode.removeChild(s);
    } catch (e) {
      // ignore
    }
  }

  injectHook();

  // Relay messages between page and background
  window.addEventListener('message', async (evt) => {
    const data = evt?.data;
    if (!data || data.__chan !== CHANNEL_FROM_PAGE) return;
    // request/commands from page hook
    switch (data.cmd) {
      case 'requestState': {
        chrome.runtime.sendMessage({ type: 'getState' }, (resp) => {
          if (resp?.ok) {
            window.postMessage({ __chan: CHANNEL_FROM_EXT, cmd: 'state', payload: resp.data }, '*');
          }
        });
        break;
      }
      case 'log': {
        const payload = data.payload || {};
        chrome.runtime.sendMessage(
          {
            type: 'log',
            url: payload.url,
            method: payload.method,
            ruleId: payload.ruleId,
            event: payload.event,
            note: payload.note,
            sample: payload.sample
          },
          () => {}
        );
        break;
      }
      default:
        break;
    }
  });

  // Receive state updates from background via direct message
  chrome.runtime.onMessage.addListener((msg) => {
    if (msg?.type === 'stateUpdated') {
      window.postMessage({ __chan: CHANNEL_FROM_EXT, cmd: 'state', payload: msg.payload }, '*');
    }
  });

  // Also forward storage changes (fallback path)
  chrome.storage.onChanged.addListener((changes, area) => {
    if (area === 'local' && changes[STATE_KEY]?.newValue) {
      window.postMessage({ __chan: CHANNEL_FROM_EXT, cmd: 'state', payload: changes[STATE_KEY].newValue }, '*');
    }
  });

  // Request initial state as early as possible
  chrome.runtime.sendMessage({ type: 'getState' }, (resp) => {
    if (resp?.ok) {
      window.postMessage({ __chan: CHANNEL_FROM_EXT, cmd: 'state', payload: resp.data }, '*');
    }
  });
})();